﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Order
    {
        public string OrderId { get; set; }
        public Customer Customer { get; set; }
        public List<OrderDetails> Details { get; set; } = new List<OrderDetails>();
        public DateTime OrderDate { get; set; }

        public decimal TotalAmount => Details.Sum(d => d.Amount);

        public Order(string orderId, Customer customer, DateTime orderDate)
        {
            OrderId = orderId;
            Customer = customer;
            OrderDate = orderDate;
        }

        public void AddDetail(OrderDetails detail)
        {
            if (Details.Contains(detail))
            {
                throw new ArgumentException("订单明细已存在");
            }
            Details.Add(detail);
        }

        public void RemoveDetail(Product product)
        {
            var detail = Details.FirstOrDefault(d => d.Product.Equals(product));
            if (detail == null)
            {
                throw new ArgumentException("订单中不存在该商品的明细");
            }
            Details.Remove(detail);
        }

        public override bool Equals(object obj)
        {
            return obj is Order order &&
                   OrderId == order.OrderId;
        }

        public override int GetHashCode()
        {
            return OrderId?.GetHashCode() ?? 0;
        }

        public override string ToString()
        {
            string details = string.Join("\n  ", Details.Select(d => d.ToString()));
            return $"订单号: {OrderId}, 客户: {Customer}, 订单日期: {OrderDate:yyyy-MM-dd}\n" +
                   $"订单明细:\n  {details}\n" +
                   $"总金额: {TotalAmount:C}";
        }

        public int CompareTo(Order other)
        {
            return OrderId.CompareTo(other.OrderId);
        }
        public object Clone()
        {
            var newOrder = new Order(this.OrderId,
                                   new Customer(this.Customer.CustomerId, this.Customer.Name),
                                   this.OrderDate);

            // 复制订单明细
            foreach (var detail in this.Details)
            {
                newOrder.AddDetail(new OrderDetails(
                    new Product(detail.Product.ProductId, detail.Product.Name, detail.Product.Price),
                    detail.Quantity));
            }

            return newOrder;
        }
    }
}
